//
//  AppDelegate.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/10.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "AppDelegate.h"
#import "MyTabBarController.h" 
#import "WXApi.h"
#import "homeViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "IQKeyboardManager.h"
@interface AppDelegate ()<WXApiDelegate>{

    NSString *str;
}


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payWayNotification:) name:@"payWay" object:nil];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;//这个是点击空白区域键盘收缩的开关
    manager.enableAutoToolbar = NO;//这个是它自带键盘工具条开关
//    UIViewController *emptyView =[[UIViewController alloc]init];
//    emptyView.view.backgroundColor=[UIColor whiteColor];
//    self.window.rootViewController = emptyView;
    [self.window makeKeyAndVisible];
    
    UINavigationBar *bar = [UINavigationBar appearance];
    
    bar.barStyle=UIBarStyleBlackTranslucent;
    
    //设置显示的颜色
    bar.barTintColor =[ZJCModel colorWithString:@"222222"];
    
    //设置字体颜色
    bar.tintColor = [UIColor whiteColor];
    
    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    // TAB BAR
    self.tabBarController = [[MyTabBarController alloc] init];
    self.window.rootViewController = self.tabBarController;
    self.window.backgroundColor = [UIColor whiteColor];
    
    
     [WXApi registerApp:@"wx5b8e9d0c74558226"];
        
    return YES;
}

//支付宝回掉

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    /*! @brief 处理微信通过URL启动App时传递的数据
     *
     * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。
     * @param url 微信启动第三方应用时传递过来的URL
     * @param delegate  WXApiDelegate对象，用来接收微信触发的消息。
     * @return 成功返回YES，失败返回NO。
     */
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSLog(@"result = %@",resultDic);
            
            if ([resultDic[@"resultStatus"]isEqualToString:@"9000"]) {
                
                if ([str isEqualToString:@"yes"]) {
                    
                    [PublicFunction showAlert:nil message:@"支付成功" duration:5.0f];
                    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"pop",@"ALIPay",@"payWay", nil];
                    NSNotification *notification =[NSNotification notificationWithName:@"pop" object:nil userInfo:dict];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }else{
                    
                    [PublicFunction showAlert:nil message:@"支付成功" duration:5.0f];
                    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"no",@"pop",@"ALIPay",@"payWay", nil];
                    NSNotification *notification =[NSNotification notificationWithName:@"pop" object:nil userInfo:dict];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }
                
            }else{
            
                NSLog(@"支付失败");
                [PublicFunction showAlert:nil message:@"支付失败" duration:5.0f];
            }
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else{
    
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;

    
}

//微信回调方法
-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = @"发送媒体消息结果";
    }
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        switch (resp.errCode) {
            case WXSuccess:{
                
                strMsg = @"恭喜您，支付成功!";
                
                if ([str isEqualToString:@"yes"]) {
                    
                    NSLog(@"支付成功");
                    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"pop",@"WXPay",@"payWay", nil];
                    NSNotification *notification =[NSNotification notificationWithName:@"pop" object:nil userInfo:dict];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }else{
                
                    NSLog(@"支付成功");
                    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"no",@"pop",@"WXPay",@"payWay", nil];
                    NSNotification *notification =[NSNotification notificationWithName:@"pop" object:nil userInfo:dict];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }
                
                break;
            }
            case WXErrCodeUserCancel:{
                
                [PublicFunction showAlert:nil message:@"已取消支付!" duration:5.0f];
                strMsg = @"已取消支付!";
                
                break;
            }
            default:{
                
                [PublicFunction showAlert:nil message:@"支付失败!" duration:5.0f];
                strMsg = [NSString stringWithFormat:@"支付失败 !"];
                
                break;
            }
        }
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
}

- (void)payWayNotification:(NSNotification *)text{

    if ([text.userInfo[@"payWay"]isEqualToString:@"yes"]) {
        
        str = @"yes";
    }else{
    
        str = @"no";
    }
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

//storyBoard view自动适配
+ (void)storyBoradAutoLay:(UIView *)allView
{
    for (UIView *temp in allView.subviews) {
        temp.frame = CGRectMake1(temp.frame.origin.x, temp.frame.origin.y, temp.frame.size.width, temp.frame.size.height);
        for (UIView *temp1 in temp.subviews) {
            temp1.frame = CGRectMake1(temp1.frame.origin.x, temp1.frame.origin.y, temp1.frame.size.width, temp1.frame.size.height);
            for (UIView *temp2 in temp1.subviews) {
                temp2.frame = CGRectMake1(temp2.frame.origin.x, temp2.frame.origin.y, temp2.frame.size.width, temp2.frame.size.height);
            }
        }
    }
}

//修改CGRectMake
CG_INLINE CGRect
CGRectMake1(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
    CGRect rect;
    rect.origin.x = (x);
    rect.origin.y = (y);
    rect.size.width = (width);
    rect.size.height = (height);
    return rect;
}


@end
